package pl.edu.pw.MidEmu.Samples.MidasChat.UI.Controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;

import midas.mw.interfaces.Mw;
import pl.edu.pw.MidEmu.Base.Controllers.BaseController;
import pl.edu.pw.MidEmu.Integration.MidEmuApplication;
import pl.edu.pw.MidEmu.Samples.MidasChat.Common.Consts;
import pl.edu.pw.MidEmu.Samples.MidasChat.Logic.Send;
import pl.edu.pw.MidEmu.Samples.MidasChat.UI.Views.ChatFrameView;

/**
 * Class representing controller for chat frame
 * @author Mateusz Starodab
 *
 */
public class ChatFrameController extends BaseController<ChatFrameView> implements ActionListener, WindowListener
{
	private Send sender;

	/**
	 * Default constructor
	 * @param middlewareInterface
	 */
	public ChatFrameController(Mw middlewareInterface)
	{
		sender = new Send(middlewareInterface);
	}

	@Override
	/**
	 * Mouse event handler
	 */
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() instanceof JButton)
		{
			JButton button = (JButton) e.getSource();
			if (button.getName().equals(Consts.ChatFrame_btnSend))
			{
				if (getView().validate())
				{
					if (sender.sendMessage(getView().getClassName(), getView().getMessageText(), getView().getValueType(), getView().getValue(), getView().getOperator()) == 0)
					{
						getView().clearMessage();
					}
					else
					{
						getView().reportSendingFailure();
					}
				}
			}
			else if (button.getName().equals(Consts.ChatFrame_btnSensors))
			{
				getView().showSensors(MidEmuApplication.getInstance().getSensors());
			}
		}
	}

	@Override
	/**
	 * Window event handler
	 */
	public void windowActivated(WindowEvent arg0)
	{
		// TODO Auto-generated method stub

	}

	@Override
	/**
	 * Window event handler
	 */
	public void windowClosed(WindowEvent arg0)
	{
		// TODO Auto-generated method stub

	}

	@Override
	/**
	 * Window event handler
	 */
	public void windowClosing(WindowEvent arg0)
	{
		sender.terminate();
		getView().terminate();
	}

	@Override
	/**
	 * Window event handler
	 */
	public void windowDeactivated(WindowEvent arg0)
	{
		// TODO Auto-generated method stub

	}

	@Override
	/**
	 * Window event handler
	 */
	public void windowDeiconified(WindowEvent arg0)
	{
		// TODO Auto-generated method stub

	}

	@Override
	/**
	 * Window event handler
	 */
	public void windowIconified(WindowEvent arg0)
	{
		// TODO Auto-generated method stub

	}

	@Override
	/**
	 * Window event handler
	 */
	public void windowOpened(WindowEvent arg0)
	{
		// TODO Auto-generated method stub

	}

}
